//
//  KSVideoUtil.m
//  KSObjcUtilDemo
//
//  Created by Mac on 2020/5/14.
//  Copyright © 2020 kong. All rights reserved.
//

#import "KSVideoUtil.h"
#import "KSFileUtil.h"
#import "KSDateUtil.h"
#import <AVKit/AVKit.h>

@implementation KSVideoUtil

//视频转为mp4
void ks_videoToMp4(NSURL* source,KSVideoTransformComplete complete){
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:source options:nil];
    
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
        
        NSString *dateStr = ks_strFromDate([NSDate date], @"yyyy_MM_dd_HH_mm_ss",nil);
        
        NSString *resultPath = [ks_documentPath() stringByAppendingFormat:@"/%@.mp4",dateStr];
        
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset
                                                                               presetName:AVAssetExportPresetMediumQuality];
        exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        exportSession.shouldOptimizeForNetworkUse = YES;
        
        [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
         {
            dispatch_async(dispatch_get_main_queue(), ^{
                complete(exportSession.outputURL,exportSession.error,exportSession.status);
            });
        }];
    }
}

//获取视频第一帧
void ks_firstFrame(NSURL* source, CGSize size, KSVideoFirstFrameComplete complete){
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:source options:opts];
        AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
        generator.appliesPreferredTrackTransform = YES;
        generator.maximumSize = CGSizeMake(size.width, size.height);
        NSError *error = nil;
        CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
        UIImage* image = [UIImage imageWithCGImage:img];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                complete? complete(image) : NO;
            }else{
                complete ? complete(nil) : NO;
            }
        });
    });
}

@end
